class Disc < ActiveRecord::Base

  #Relations & Associations
  belongs_to :edition
  has_many   :songs, :order => "track", :dependent => :destroy
  has_many   :edits
  
  accepts_nested_attributes_for :songs,:reject_if => lambda { |a| a[:title].blank? && a[:track].blank? && a[:length].blank? }, :allow_destroy => true
  
  #Constants
  DISC_FORMATS = %w(CD DVD Vinyl Cassette Digitial)

  #Validations
  validates_presence_of :edition_id
  validates_inclusion_of :format,
                         :in => DISC_FORMATS,
						 :message => "Not a valid disc format.",
                         :allow_blank => true,
						 :allow_nil => true
  validate :check_songs
  
  #Callbacks
  before_save :link_artist
  
  # Overrides default to_string behavior. Returns disc title
  def to_s
    return title
  end
  
  # There appears to be some sort of Rails method called format that
  # was interfering on certain calls to disc. This forces it to read the
  # format column from the disc record.
  def format
    read_attribute("format")
  end
  
  private
  
  #Ensure there are actually songs associated with the disc,
  # if not fail validation.
  def check_songs
    if songs.empty?
	  errors.add_to_base("A disc cannot be empty. Please add some songs before submitting.")
	end
  end
  
  #If this is a new song, add all artists associated with the
  #release to that song
  def link_artist
      songs.each do |song|
	    if song.new_record?
		  edition.release.artists.each { |a| song.artists << a }
		end
	  end
  end
  
end
